import zlib
import math
import traceback
def get_crc32(data, max_length):
    try:
        crc32 = hex(zlib.crc32(data)).replace('0x','')
        if len(crc32) < max_length:
            return crc32.rjust(max_length,'0')
        elif len(crc32) > max_length:
            return crc32[:max_length]
        else:
            return crc32
    except:
        return '0' * max_length

def hex_to_int(hex):
    try:
        return int('0x' + hex, 16)
    except:
        return 0


def int_to_hex(int, max_length=6):
    try:
        return hex(int).replace('0x', '').rjust(max_length, '0')
    except:
        return '00000000'

def split_bytes_by_length(data, length):
    '''
    使用长度对字节进行分割
    :param data: 欲被分割的字节集
    :param length: 分割长度
    :return: 分割后的字节集列表
    '''
    try:
        split_list = []
        data_length = len(data)
        count = math.ceil(data_length / length)
        for i in range(0, count):
            start = i * length
            end = start + length
            split_list.append(data[start:end])
        return split_list
    except:
        traceback.print_exc()
        return False